<html>

<head>
      <meta charset="utf-8">
      <title>canvas图片压缩</title>
</head>

<body>
      <img width="100%" src="131.png">
      <canvas id="canvas" style="display: none;"></canvas>
      <img id="preview" src="">
      <img id="source" src= '131.png' style="display: none;" onload="imgld()">
      <script>

            var canvas = document.getElementById('canvas');
            var source = document.getElementById('source');
            var preview = document.getElementById('preview');

            source.onload = function imgld() {

                  //图片宽高
                  var width = source.width;
                  var height = source.height;

                  //宽高比例
                  var scale = width / height;

                  //初始化 canvas
                  var context = canvas.getContext('2d');

                  //裁剪前的图片 格式
                  var sx = 0;
                  var sy = 0;
                  var sWidth = width;
                  var sHeight = height;

                  //裁剪后的图片 格式
                  var dx = 0;
                  var dy = 0;
                  var dWidth = 800;
                  var dHeight = dWidth / scale;

                  //图片清晰度
                  var quality = 0.8;

                  canvas.width = dWidth;
                  canvas.height = dHeight;

                  //压缩
                  context.drawImage(source, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

                  //图片base 64
                  var dataUrl = canvas.toDataURL('image/jpg', quality);

                  //预览压缩后的图片
                  preview.src = dataUrl;
            };

      </script>

</body>

</html>